'''
Created on 2012-9-5

@author: Administrator
'''
import logging
import time
import datetime
import os

from common.sessions import Session
from google.appengine.ext.webapp import template

_TRACE = "[trace]"
_FOMATTER_SEPERATOR = "       "
_USER_NAME = 'username'
_DEFAULT_INDEX = 'templates/index.html'
_TEST_STRING = """

                This is test string
                This is test string
                This is test string
                This is test string
                This is test string
                This is test string
                This is test string
                
               """

class StringFormatter( object ):
    def __init__( self, countperline = 1 , *args ):
        self.countperline = countperline
        self.contents = args
          
    def get_string( self ):
        str_ = "\n"
        counter = 0
        for text in self.contents:
            counter = counter + 1
            str_ += str( text ) + _FOMATTER_SEPERATOR
            if counter % self.countperline == 0 and counter != 0:
                str_ += '\n'
                
        if str_[-1:] == '\n':
            pass
        else:
            str_ += '\n'
            
        return str_
    
    def __str__( self ):
        return self.get_string()
        
class Logger( object ):
    def info( self , user_text = "", user_data = "", model = __name__, file_ = __file__ ):
        now = datetime.datetime.now()
        log = StringFormatter( 1, "[time]" + str( now ), "[text]" + str( user_text ), "[data]" + str( user_data ), "[model]" + str( model ) , "[file]" + str( file_ ) ).get_string()
        logging.info( log )
        print log
        return log
    
    def error( self , user_text = "", user_data = "", model = __name__, file_ = __file__ ):
        now = datetime.datetime.now()
        log = StringFormatter( 1, "[time]" + str( now ), "[text]" + str( user_text ), "[data]" + str( user_data ), "[model]" + str( model ) , "[file]" + str( file_ ) ).get_string()
        logging.error( log )
        print log
        return log
        
    def log_submodel( self, model = "" , user_text = "" ):
        now = datetime.datetime.now()
        log = StringFormatter( 1, "[time]" + str( now ), "[submodel]" + str( __name__ ) + "." + str( model ), "[text]" + user_text )
        logging.info( log )
        return log
    
    def get_time_second_accuracy( self ):
        return time.strftime( "%Y-%m-%d;%H:%M:%S", time.localtime( time.time() ) )
    
def validate_login_session( handler ):
    handler.session = Session()
    for _USER_NAME in handler.session:
        return True
    else:
        return False

def do_render( handler, template_ = _DEFAULT_INDEX, hint = {}, ):
    '''
        render HTML page by out stream and path in give handler
        !the HTML page template will be find from the templates root folder(/templates)
    '''
    logger = Logger()
    path = handler.request.path
    if path.find( '/' ) == 0:
        path = path[1:]
    temp = os.path.join( os.path.dirname( __file__ ), "../templates/", path )
    
    if not os.path.isfile( temp ):
        logger.error( "error path : " + str( path ) + ",temp : " + str( temp ) )
        temp = os.path.join( os.path.dirname( __file__ ), "../" , _DEFAULT_INDEX )
        page = template.render( temp, hint, debug = True )
        handler.response.out.write( page )
        return False
    
    temp = os.path.join( os.path.dirname( __file__ ), "../", template_ )
    
    logger.info( "path : " + str( path ) + ",temp : " + str( temp ) )
    page = template.render( temp, hint, debug = True )
    handler.response.out.write( page )
    
    return True

def render_template( writer, template_ = _DEFAULT_INDEX, hint = {} ):
    '''
        render a HTML page, using given stream and given template path
        !template_ is the template path from root folder(/templates)
    '''
    logger = Logger()
    temp = os.path.join( os.path.dirname( __file__ ), "../", template_ )
    
    if not os.path.isfile( temp ):
        logger.error( "error template : " + temp )
        temp = os.path.join( os.path.dirname( __file__ ), "../", _DEFAULT_INDEX )
        page = template.render( temp, hint, debug = True )
        writer.write( page )
        return False
    
    logger.info( "render template : " + temp )
    page = template.render( temp, hint, debug = True )
    writer.write( page )
    return True
